package com.yumo.kangchenjunga.coupon.v1;

import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort.Direction;
import org.springframework.data.web.PageableDefault;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import com.yumo.kangchenjunga.activity.NoSuchActivityException;
import com.yumo.kangchenjunga.exception.controller.HttpNotFoundException;
import com.yumo.kangchenjunga.user.NoSuchUserException;

@RestController
@RequestMapping("/api/v1/coupons")
public final class CouponController {

	@Autowired
	private CouponService service;
	@Autowired
	private CouponListService couponListService;

	@GetMapping("/{id}")
	public CouponEntity queryById(@PathVariable int id) throws HttpNotFoundException {
		try {
			return service.queryById(id);
		} catch (NoSuchCouponException e) {
			throw HttpNotFoundException.build(e, "优惠券 [ id: %d ] 不存在。", id);
		}
	}

	@GetMapping("/")
	public Iterable<CouponEntity> list() {
		return service.list();
	}

	@GetMapping(path = "/", params = { "paged" })
	public Page<CouponEntity> page(
			@PageableDefault(page = 0, size = 10, sort = "id", direction = Direction.DESC) Pageable pageable) {
		return service.page(pageable);
	}

	@GetMapping("/service/query")
	public Page<CouponEntity> query(@RequestBody CouponEntity coupon,
			@PageableDefault(page = 0, size = 10, sort = "id", direction = Direction.DESC) Pageable pageable) {
		return service.query(coupon, pageable);
	}
	
	@PostMapping("/services/generate/{activityId}")
	public int generate(@PathVariable int activityId, @RequestParam int amount, @RequestParam int termByDay)
			throws HttpNotFoundException {
		try {
			return service.generate(activityId, amount, termByDay);
		} catch (NoSuchActivityException e) {
			throw HttpNotFoundException.build(e, "权益 [ id: %d ] 不存在。", activityId);
		}
	}

	@PostMapping("/services/redeem")
	@Deprecated
	public List<CouponLogEntity> redeem(@RequestParam String opStore,
			@RequestParam String remark, @RequestParam int opUserId, @RequestBody List<String> couponCodes)
			throws HttpNotFoundException {
		try {
			return service.redeem(couponCodes, opStore, remark, opUserId);
		} catch (NoSuchUserException e) {
			throw HttpNotFoundException.build("企业用户 [ id: %d ] 不存在。", opUserId);
		}
	}

	@PostMapping("/{couponCode}/verify")
	public VerifyCouponVo verify(@PathVariable String couponCode, @RequestParam String opStore,
			@RequestParam int companyId, @RequestParam int opUserId) throws HttpNotFoundException {
		try {
			return service.verify(couponCode, opStore, companyId, opUserId);
		} catch (NoSuchUserException e) {
			throw HttpNotFoundException.build(e, "企业用户 [ companyId: %d, userId: %d ] 不存在。", companyId, opUserId);
		}
	}

	@PostMapping("/services/allocate/{activityId}/by-customer-level/{customerLevel}")
	public AllocateResultVo allocateByCustomerLevel(@PathVariable int activityId,
			@PathVariable int customerLevel, @RequestParam int perCustomer) throws HttpNotFoundException {
		try {
			return service.allocateByCustomerLevel(activityId, customerLevel, perCustomer);
		} catch (NoSuchActivityException e) {
			throw HttpNotFoundException.build(e, "权益 [ id: %d ] 不存在。", activityId);
		}
	}

	@PostMapping("/services/allocate/{activityId}/by-customer")
	public AllocateResultVo allocateByCustomer(@PathVariable int activityId, @RequestBody List<Integer> customerIds,
			@RequestParam int perCustomer) throws HttpNotFoundException {
		try {
			return service.allocateByCustomer(activityId, customerIds, perCustomer);
		} catch (NoSuchActivityException e) {
			throw HttpNotFoundException.build(e, "权益 [ id: %d ] 不存在。", activityId);
		}
	}
	
	@GetMapping("/obtainments/export")
	public void exportSettlePreview(HttpServletRequest request, HttpServletResponse response) throws IOException {
		response.setContentType("application/force-download");
		response.addHeader("Content-Disposition", String.format("attachment;fileName=\"%s\"",
				new String("已领取优惠券.xls".getBytes(StandardCharsets.UTF_8), StandardCharsets.ISO_8859_1)));
		CouponListItemVo coupon = new CouponListItemVo();
		coupon.activityId = StringUtils.isBlank(request.getParameter("activityId")) ? null
				: Integer.valueOf(request.getParameter("activityId"));
		coupon.couponCode = StringUtils.isBlank(request.getParameter("couponCode")) ? null : request.getParameter("couponCode");
		couponListService.obtainmentExport(coupon, response.getOutputStream());
	}

}
